import io.netty.buffer.ByteBuf
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}

/**
  * Created by IntelliJ IDEA.
  * Programmer : John Zn
  * Date : 2016/4/14 0014
  * Time : 22:11
  * Discribtion : 
  */
class ServerHandler extends ChannelInboundHandlerAdapter {
  override def channelActive(ctx: ChannelHandlerContext): Unit = {
    println("server actived")
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
    println("server exceptionCaught")
    ctx.close()
  }

  override def channelRead(ctx: ChannelHandlerContext, msg: scala.Any): Unit = {
    /*
    * 字符串可以直接用来读写
    * */
    //        println(msg)
    //        println(msg.getClass)
    //        ctx.write(msg)
    msg match {
      case message: String => {
        println(s"string: $message");
        ctx.write(" string return ")
      }
      case NettyMsg(message) => println(s"NettyMsg: $message"); ctx.write(NettyMsg(" nettyMessage return"))
    }
    //    val byteBuf = msg.asInstanceOf[ByteBuf]
    //    val bytes = new Array[Byte](byteBuf.readableBytes())
    //    val message = new String(bytes, "UTF-8")
    //    byteBuf.readBytes(bytes)
    //    println("aaaa")
    //    ctx.write(message)
    //    println("bbbb")
  }

  override def channelRegistered(ctx: ChannelHandlerContext): Unit = {
    println("server point registered")
  }

  override def channelReadComplete(ctx: ChannelHandlerContext): Unit = {
    println("server read complete")
    ctx.flush()
  }
}
